package org.nvframe;

import org.jbox2d.collision.AABB;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.World;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.SlickException;
import org.nvframe.event.EventService;
import org.nvframe.event.eventtype.UpdateEvent;
import org.nvframe.manager.CollisionManager;
import org.nvframe.manager.RegisterManager;

public abstract class NVFramePhysicsGame extends NVFrameGame {
	
	private int iterations = 10;
	private float timestep = 1f / 100f;
	
	protected World world;
	
	public NVFramePhysicsGame(String title) {
		super(title);
		
		createWorld();
		
		// add world to register for later use
		RegisterManager.getInstance().setOption("world", world);
	}
	
	private void createWorld() {
		boolean doSleep = true;
		
		// kill gravity for a topdown game
		Vec2 gravity = new Vec2(0.0f, 0.0f);
		
		AABB worldAABB = new AABB();
		worldAABB.lowerBound.set(-10000, -10000);
		worldAABB.upperBound.set(10000, 10000);
		
		world = new World(worldAABB, gravity, doSleep);
		world.setContinuousPhysics(true);
		
		// register collisionManager
		CollisionManager collisionManager = CollisionManager.getInstance();
		collisionManager.registerForWorld(world);
		world.setContactListener(collisionManager);
	}

	@Override
	public void update(GameContainer gc, int delta) throws SlickException {
		if(pauzeKey != 0 && gc.getInput().isKeyPressed(pauzeKey))
			togglePauze();
		
		if(pauze)
			return;
		
		// update physics every timestep (default 1/60)
		world.step(timestep, iterations);
		
		EventService.getInstance().fireEvent(new UpdateEvent(gc, delta));
	}
}
